home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2060 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: info.uah.edu!oreo!gbacon
  2. From: gbacon@oreo (Greg Bacon)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: union ?
  5. Date: 18 Jan 1996 20:20:52 GMT
  6. Organization: The University of Alabama in Huntsville
  7. Message-ID: <4dma34$bsi@info.uah.edu>
  8. References: <4dkigi$c29@linet02.li.net>
  9. Reply-To: gbacon@CS.UAH.Edu
  10. NNTP-Posting-Host: oreo.aspire.cs.uah.edu
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. Don Matthews (don@newshost.li.net) wrote:
  14. : A union consist of many different variables.
  15. : But at any one time it can only hold one of those variables.
  16. : Is that correct?
  17.  
  18. Errr... not exactly.  You see, given any chunk of memory (which will
  19. consist of just 1's and 0's), the computer doesn't know if it's
  20. character data, integer data, or float data; it's all in how the
  21. programmer interprets it.
  22.  
  23. A union is identical to a structure with the exception that all the
  24. offsets are zero.  So while you can send data into the union as one
  25. type, you can get it out as another.  For example, a common way
  26. of getting around the byte-order problem for your data files looks
  27. something like this.
  28.  
  29. {
  30.    union
  31.    {
  32.       char c[4];
  33.       int  i;
  34.    } u;
  35.  
  36.    copy_string_data(string, u.c);
  37.  
  38.    write_to_file(htonl(u.i));
  39.  
  40. Of course, string is some (likely) character string outside this
  41. scope and the copy_string_data() function just puts 4 chars into
  42. the array it gets a pointer to.  htonl() you find on UNIX platforms.
  43. It converts its argument from host to network byte order.  Voila!
  44. Instant portable data files.
  45.  
  46. So, you see, there isn't "room" enough in the same union for 4 chars
  47. _and_ an int, it's just an easy way of interpreting the same data
  48. in multiple ways.
  49.  
  50. Hope this helps,
  51. Greg
  52. --
  53. Greg Bacon <gbacon@cs.uah.edu>
  54. University of Alabama in Huntsville
  55. CS Department Systems Support Team
  56.